package com.example.questionnaires.controller;

import com.example.questionnaires.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.annotation.PostConstruct;

@Slf4j
@RestController
@RequestMapping("/api/upload")
public class FileController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url}")
    private String uploadUrl;

    @PostConstruct
    public void init() {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            if (uploadDir.mkdirs()) {
                log.info("创建上传目录成功: {}", uploadPath);
            } else {
                log.error("创建上传目录失败: {}", uploadPath);
            }
        }
        log.info("上传目录: {}", uploadPath);
    }

    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + extension;

            // 保存文件
            File destFile = new File(uploadPath + File.separator + newFileName);
            file.transferTo(destFile);

            // 返回文件访问URL
            String fileUrl = uploadUrl + "/" + newFileName;
            return Result.success(fileUrl);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败");
        }
    }
} 